package com.qf.cx.simplenms.topic.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qf.cx.simplenms.topic.api.Topic;
import com.qf.cx.simplenms.topic.api.TopicManager;
import com.qf.cx.simplenms.topic.model.TopicModel;
import com.qf.cx.simplenms.topic.spi.TopicSpi;

public class TopicManagerImpl implements TopicManager {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private Map<String, TopicSpi> map = new HashMap<>();

	@Override
	public synchronized void updateCache(List<TopicModel> list) {
		for (Iterator<Entry<String, TopicSpi>> it = map.entrySet().iterator(); it.hasNext();) {
			Entry<String, TopicSpi> e = it.next();

			boolean delete = true;
			for (TopicModel topicModel : list) {
				if (topicModel.getName().equals(e.getKey())) {
					delete = false;
					break;
				}
			}
			if (delete) {
				TopicSpi topic = e.getValue();
				topic.forceStop();
				it.remove();
				logger.debug("delete topic '{}'", e.getKey());
			}
		}

		for (TopicModel t : list) {
			TopicSpi topic = map.get(t.getName());
			if (topic == null) {
				topic = new TopicImpl(t);
				map.put(t.getName(), topic);
				logger.debug("add topic '{}'", t.getName());
			} else {
				topic.updateTopicModel(t);
				logger.debug("update topic '{}'", t.getName());
			}
		}
	}

	@Override
	public String dump() {
		StringBuilder sb = new StringBuilder();
		sb.append("<h1>topics</h1></br>");
		for (Entry<String, TopicSpi> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("</br>").append(entry.getValue().dump()).append("</br>");
		}
		sb.append("</br>");
		return sb.toString();
	}

	@Override
	public Topic getTopic(String name) {
		Topic topic = map.get(name);
		if (topic == null) {
			logger.warn("no Topic named '{}'", name);
		}
		return topic;
	}

}
